package gptma.fo.controler.project;

import gptma.bo.model.project.Project;
import gptma.bo.model.request.ClientRequest;
import gptma.bo.model.task.Task;
import gptma.bo.services.project.ProjectServices;
import gptma.bo.services.request.ClientRequestServices;
import gptma.fo.cdi.ViewScoped;
import gptma.fo.controler.WebPage;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Named;
import org.primefaces.event.ItemSelectEvent;

/**
 * 
 * @author xcl
 */
@Named
@ViewScoped
public class ProjectDetailsPage extends WebPage implements Serializable {

	private static final long serialVersionUID = -9137135386188842043L;

	@EJB
	private ProjectServices projectServices;

	@EJB
	private ClientRequestServices clientRequestServices;

	private Project project;

	private float soldCharge;

	private float charge;

	private float etc;

	private List<ClientRequest> requests;

	private List<ClientRequestBean> requestBeans;

	private List<Task> tasks;

	private String chartMessage;

	public void initProjectDetailsPage() {
		project = session.getSelectedProject();

		float[] data = projectServices.getProjectCharge(project);
		soldCharge = data[0];
		charge = data[1];
		etc = data[2];

		requests = projectServices.findRequests(project);
		tasks = projectServices.findAssociatedTasks(project);

		requestBeans = new ArrayList<ClientRequestBean>(requests.size());
		float requestCharge;
		for (ClientRequest req : requests) {
			requestCharge = clientRequestServices.getSoldRequestCharge(req);
			requestBeans.add(new ClientRequestBean(req, requestCharge));
		}
	}

	public String update() {
		try {
			projectServices.saveProject(project);
			addInfoMessageFromKey("infoModifSummary");
		} catch (Exception e) {
			addErrorMessageFromKey("errModifSummary");
		}

		return null;
	}

	public void chartItemSelected(ItemSelectEvent event) {
		ClientRequestBean selected = requestBeans.get(event.getItemIndex());
		chartMessage = getLocalisedMessage("proDetailsRepartitionSelected",
				selected.getClientRequest().getClientReference(),
				selected.getCharge());
	}

	public Project getProject() {
		return project;
	}

	public void setProject(Project project) {
		this.project = project;
	}

	public float getCharge() {
		return charge;
	}

	public float getEtc() {
		return etc;
	}

	public float getSoldCharge() {
		return soldCharge;
	}

	public List<ClientRequest> getRequests() {
		return requests;
	}

	public List<Task> getTasks() {
		return tasks;
	}

	public List<ClientRequestBean> getRequestBeans() {
		return requestBeans;
	}

	public String getChartMessage() {
		return chartMessage;
	}

}
